from rest_framework import serializers
from user.models import UserModel
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token["username"] = str(user.username)
        token["password"] = str(user.password)
        token["mobile"] = str(user.mobile)
        token["email"] = str(user.email)
        return token

class UserSerializer(serializers.ModelSerializer):
    re_password = serializers.CharField(write_only=True, required=True)

    gender_display = serializers.CharField(source="get_gender_display", read_only=True)
    token = serializers.CharField(read_only=True)
    refresh = serializers.CharField(read_only=True)

    class Meta:
        model = UserModel
        fields = ('id', 'username', 'password', 're_password', 'mobile', 'email', 'gender', 'gender_display', 'age',
                  'avatar', 'token', 'refresh')

    def validate(self, attrs):
        request = self.context["request"]
        origin_username = request.user.username
        print(request.user)
        password = attrs.get("password", None)
        re_password = attrs.get("re_password", None)
        username = attrs.get("username")
        if username != origin_username:
            if UserModel.objects.filter(username=username):
                raise serializers.ValidationError(detail="用户名不能重复", code="username")
        if password != re_password:
            raise serializers.ValidationError(detail="两次密码输入不同", code="re_password")
        return attrs

    def create(self, validated_data):
        username = validated_data["username"]
        password = validated_data["password"]
        mobile = validated_data.get("mobile", None)
        email = validated_data.get("email", None)
        user = UserModel.objects.create_user(
            username=username,
            password=password,
            mobile=mobile,
            email=email
        )

        refresh = CustomTokenObtainPairSerializer.get_token(user)

        user.refresh = str(refresh)
        user.token = str(refresh.access_token)
        return user

# class UserDetailSerializer(serializers.ModelSerializer):
#     username = serializers.CharField(source="user.username")
#     mobile = serializers.CharField(source="user.mobile")
#     email = serializers.CharField(source="user.email")
#
#     password = serializers.CharField(source="user.username", write_only=True)
#
#     class Meta:
#         model = UserDetail
#         fields = ["username", "mobile", "email", "password", "avatar", "gender", "age"]

